/**
 * Project: TacticaPescaditos
 * File: Segment2D.java
 */
package org.javahispano.javacup.tacticas_aceptadas.Pescaditos.com.chidotronics.javacup.geometrics;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

/**
 * @author Carlos Alberto
 * class: Segment2D
 */
public class Segment2D extends Line2D.Double {

	/**
	 * serialVersionUID:
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	public Segment2D() {
	}

	/**
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	public Segment2D(double arg0, double arg1, double arg2, double arg3) {
		super(arg0, arg1, arg2, arg3);
	}

	/**
	 * @param arg0
	 * @param arg1
	 */
	public Segment2D(Point2D arg0, Point2D arg1) {
		super(arg0, arg1);
	}
	
	public Vector2D projection(Vector2D point){
		Vector2D result = null;

		Vector2D a = new Vector2D(this.x2-this.x1,this.y2-this.y1); 
		Vector2D b = point.substract(this.getP1());
		double aa = a.dot(a);
		
		if (aa != 0) {
			double as = b.dot(a)/aa;
			if (as >=0 && as <= 1) {
				result = new Vector2D(this.x1,this.y1 ).add( a.multiply(as));
				
			}
		} 
		
		return result;
	}
	
	
	 public Vector2D intersection(Segment2D other
	 ) {
		 double d = (x1-x2)*(other.y1-other.y2) - (y1-y2)*(other.x1-other.x2);
		 if (d == 0) return null;

		 double xi = ((other.x1-other.x2)*(x1*y2-y1*x2)-(x1-x2)*(other.x1*other.y2-other.y1*other.x2))/d;
		 double yi = ((other.y1-other.y2)*(x1*y2-y1*x2)-(y1-y2)*(other.x1*other.y2-other.y1*other.x2))/d;

		 return new Vector2D(xi,yi);
	 }


	
}
